<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class CpcLimit extends Model
{


	private $deviceId;
	private $adPositionCode;
	private $adPosition;

	public function __construct($deviceId, $adPositionCode)
	{
		$this->deviceId = $deviceId;
		$this->adPosition = \App\Model\AdPosition::where('identifier', $adPositionCode)->first();
	}
	// public static function getDeviceTarget($deviceId, $adPosition)
	// {
	// 	$redis = Redis::connection('default');
	// 	$defaultChannelDailyShowTotalLimit = 1000;
	// 	$defaultChannelDailyDeviceShowTotalLimit = 6;
	// 	$defaultChannelDailyShowTotalKey = self::CPC_SOURCE_DAILY_SHOW . date('Y-m-d') . ':' . Cpc::CHANNEL_DEFAULT;

	// 	$defaultChannelDailyShowTotalCount = $redis->get($defaultChannelDailyShowTotalKey);

	// 	if ($defaultChannelDailyShowTotalCount > $defaultChannelDailyShowTotalLimit) {
	// 		return self::getExtTarget($deviceId);
	// 	}

	// 	$perDeviceDailyTotalShowKey = self::CPC_DEVICE_DAILY_SHOW . date('Y-m-d') . ":{$deviceId}";

	// 	if ($redis->incr($perDeviceDailyTotalShowKey) <= $defaultChannelDailyDeviceShowTotalLimit) {
	// 		return self::getDefaultTarget($deviceId);
	// 	} else {
	// 		return self::getExtTarget($deviceId);
	// 	}
	// }

	public function getDeviceTarget()
	{
		$defaultChannelConfigs = \App\Model\CpcConfig::where('ad_provider_id', 1)
													->where('status', \App\Model\CpcConfig::STATUS_ONLINE)
													->where('ad_position_id', 0)
													->orderBy('rank', 'desc')
													->get();
		$defaultFlag = true;
		foreach ($defaultChannelConfigs as $defaultConfig) {
			$funcName = camel_case('check_' . $defaultConfig->key);
			$ret = $defaultConfig->{$funcName}($this->deviceId);
			if (!$ret) {
				$defaultFlag = false;
			}
		}

		if ($defaultFlag) {
			return $defaultConfig->getTarget();
		}

		$otherChannelConfigs = \App\Model\CpcConfig::where('ad_position_id', $this->adPosition->id)
													->where('status', \App\Model\CpcConfig::STATUS_ONLINE)
													->orderBy('rank', 'desc')
													->get()
													->groupBy('rank');
		foreach ($otherChannelConfigs as $rank => $configs) {
			if (count($configs) > 1) {
				$configs = $configs->shuffle();
			}
			foreach ($configs as $config) {
				$funcName = camel_case('check_' . $config->key);
				$ret = $config->$funcName($this->deviceId);
				if ($ret) {
					return $config->getTarget(); 
				}
			}
		}
		$funcName = camel_case('check_' . $config->action);
		$ret = $config->$funcName($this->deviceId);
		if (!empty($ret)) {
			return $ret;
		} else {
			return 'default';
		}
	}

	public static function getDefaultTarget($deviceId)
	{
		return Cpc::CHANNEL_DEFAULT;
	}

	public static function getExtTarget($deviceId)
	{
		$channelList = Cpc::getExtChannelList();
		$key = array_rand($channelList);

		return $channelList[$key];
	}
}